package org.example.serviceoffice.controller;

import org.example.model.manage.bean.Result;
import org.example.model.manage.bean.po.Counselor;
import org.example.model.manage.bean.po.Faculty;
import org.example.model.manage.bean.po.Major;
import org.example.model.manage.bean.po.Student;
import org.example.model.manage.bean.po.security.User;
import org.example.model.manage.bean.vo.CounselorRegisterRequest;
import org.example.model.manage.bean.vo.FacultyCount;
import org.example.model.manage.bean.vo.FacultyRegisterRequest;
import org.example.model.manage.bean.vo.MajorCount;
import org.example.model.manage.bean.vo.MajorImportResult;
import org.example.model.manage.bean.vo.MajorRegisterRequest;
import org.example.model.manage.bean.vo.SchoolCount;
import org.example.model.manage.bean.vo.CreatePayRequest;
import org.example.model.manage.bean.vo.BindPayRequest;
import org.example.model.manage.bean.po.Pay;
import org.example.serviceoffice.service.PayService;
import org.example.serviceoffice.service.OfficeService;
import org.example.serviceoffice.feign.FileTransferFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.example.serviceoffice.vo.PageResult;
import org.example.serviceoffice.vo.StudentListVO;
import org.example.serviceoffice.vo.CounselorWithMajorVO;

import java.util.List;

@RestController
@PreAuthorize("hasAnyAuthority('office')")
public class OfficeController {

    @Autowired
    private OfficeService officeService;

    @Autowired
    private PayService payService;

    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private FileTransferFeignClient fileTransferFeignClient;

    /**
     * 学生处获取学院列表
     */
    @GetMapping("/facultyList")
    public Result<List<FacultyCount>> getFacultyList() {
        List<FacultyCount> facultyList = officeService.getFacultyList();
        return Result.success(facultyList);
    }

    /**
     * 学生处获取某学院各专业学生报道信息
     */
    @GetMapping("/facultyMajorList")
    public Result<List<MajorCount>> getMajorReportListByFaculty(@RequestParam Integer facultyId) {
        List<MajorCount> majorReportList = officeService.getMajorReportListByFaculty(facultyId);
        return Result.success(majorReportList);
    }

    /**
     * 学生处统计全校学生报道信息
     */
    @GetMapping("/count")
    public Result<SchoolCount> getSchoolCount() {
        SchoolCount schoolCount = officeService.getSchoolCount();
        return Result.success(schoolCount);
    }

    /**
     * 添加学生信息
     */
    @PostMapping("/addStudent")
    public Result<Student> addStudent(@RequestBody Student student) {
        try {
            Student savedStudent = officeService.addStudent(student);
            return Result.success(savedStudent);
        } catch (IllegalArgumentException e) {
            return Result.error(10001, e.getMessage());
        } catch (Exception e) {
            return Result.error(500, "添加学生失败");
        }
    }

    /**
     * 注册学院
     */
    @PostMapping("/registerFaculty")
    public Result<Faculty> registerFaculty(@RequestBody FacultyRegisterRequest request) {
        try {
            // 检查学院是否已存在
            Faculty existing = officeService.getFacultyByName(request.getFacultyName());
            if (existing != null) {
                return Result.error(400, "学院已存在");
            }

            // 创建新学院（ID 自增，MyBatis 回填）
            Faculty newFaculty = new Faculty();
            newFaculty.setFaculty(request.getFacultyName());
            Faculty savedFaculty = officeService.createFaculty(newFaculty);

            // 自动创建学院用户账号
            User user = new User();
            user.setAccount(request.getFacultyName());
            user.setPassword(passwordEncoder.encode(request.getFacultyName())); // 密码使用学院名称并加密
            user.setType("faculty");
            user.setTypeId(savedFaculty.getId());
            officeService.createUser(user);

            return Result.success(savedFaculty);
        } catch (Exception e) {
            return Result.error(500, "注册学院失败: " + e.getMessage());
        }
    }

    /**
     * 注册辅导员
     */
    @PostMapping("/registerCounselor")
    public Result<String> registerCounselor(@RequestBody CounselorRegisterRequest request) {
        try {
            for (CounselorRegisterRequest.CounselorInfo info : request.getCounselorList()) {
                // 校验所属学院
                if (info.getFacultyId() == null) {
                    return Result.error(400, "辅导员所属学院ID不能为空");
                }
                Faculty faculty = officeService.getFacultyById(info.getFacultyId());
                if (faculty == null) {
                    return Result.error(400, "学院不存在: " + info.getFacultyId());
                }
                // 基于姓名与学院判断是否已存在（避免依赖外部传入ID）
                Counselor existing = null;
                if (info.getId() != null) {
                    existing = officeService.getCounselorById(info.getId());
                }
                if (existing == null) {
                    // 创建新辅导员（ID 由数据库自增生成）
                    Counselor newCounselor = new Counselor();
                    newCounselor.setName(info.getName());
                    newCounselor.setFaculty(faculty.getFaculty());
                    Counselor saved = officeService.createCounselor(newCounselor);

                    // 自动创建用户账号，使用回填后的 saved.id 作为 typeId
                    User user = new User();
                    user.setAccount(info.getName());
                    user.setPassword(passwordEncoder.encode(info.getName()));
                    user.setType("counselor");
                    user.setTypeId(saved.getId());
                    officeService.createUser(user);
                }
            }

            return Result.success("辅导员注册成功");
        } catch (Exception e) {
            return Result.error(500, "注册辅导员失败: " + e.getMessage());
        }
    }

    /**
     * 根据CSV文件导入辅导员信息
     */
    @PostMapping("/importCounselors")
    public Result<String> importCounselors(@RequestParam("file") MultipartFile file) {
        try {
            String result = officeService.importCounselorsFromCsv(file);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(500, "导入辅导员信息失败: " + e.getMessage());
        }
    }

    /**
     * 根据CSV文件导入学生信息
     */
    @PostMapping("/importStudents")
    public Result<String> importStudents(@RequestParam("file") MultipartFile file) {
        try {
            String result = officeService.importStudentsFromCsv(file);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(500, "导入学生信息失败: " + e.getMessage());
        }
    }

    /**
     * 根据CSV文件导入学院信息
     */
    @PostMapping("/importFaculties")
    public Result<String> importFaculties(@RequestParam("file") MultipartFile file) {
        try {
            String result = officeService.importFacultiesFromCsv(file);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(500, "导入学院信息失败: " + e.getMessage());
        }
    }

    /**
     * 根据CSV文件导入专业信息
     */
    @PostMapping("/importMajors")
    public Result<MajorImportResult> importMajors(@RequestParam("file") MultipartFile file) {
        try {
            MajorImportResult result = officeService.importMajorsFromCsv(file);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error(500, "导入专业信息失败: " + e.getMessage());
        }
    }

    /**
     * 分页获取学生列表（包含专业名字）
     */
    @GetMapping("/studentList")
    public Result<PageResult<StudentListVO>> getStudentList(@RequestParam int page, @RequestParam int size) {
        PageResult<StudentListVO> result = officeService.getStudentWithMajorNamePage(page, size);
        return Result.success(result);
    }

    /**
     * 分页获取辅导员列表（包含专业ID列表）
     */
    @GetMapping("/counselorList")
    public Result<PageResult<CounselorWithMajorVO>> getCounselorList(@RequestParam int page, @RequestParam int size) {
        PageResult<CounselorWithMajorVO> result = officeService.getCounselorWithMajorPage(page, size);
        return Result.success(result);
    }

    /**
     * 添加专业
     */
    @PostMapping("/addMajor")
    public Result<Major> addMajor(@RequestBody MajorRegisterRequest request) {
        try {
            // 校验参数
            if (request.getMajorName() == null || request.getMajorName().trim().isEmpty()) {
                return Result.error(400, "专业名字不能为空");
            }
            if (request.getFacultyName() == null || request.getFacultyName().trim().isEmpty()) {
                return Result.error(400, "学院名字不能为空");
            }

            // 根据学院名字查找学院
            Faculty faculty = officeService.getFacultyByName(request.getFacultyName());
            if (faculty == null) {
                return Result.error(404, "学院不存在: " + request.getFacultyName());
            }

            // 检查专业是否已存在
            Major existingMajor = officeService.getMajorByNameAndFacultyId(request.getMajorName(), faculty.getId());
            if (existingMajor != null) {
                return Result.error(400, "专业已存在: " + request.getMajorName());
            }

            // 创建新专业
            Major newMajor = new Major();
            newMajor.setMajor(request.getMajorName());
            newMajor.setFacultyId(faculty.getId());
            Major savedMajor = officeService.createMajor(newMajor);

            return Result.success(savedMajor);
        } catch (Exception e) {
            return Result.error(500, "添加专业失败: " + e.getMessage());
        }
    }

    /**
     * 删除学院
     */
    @DeleteMapping("/deleteFaculty/{id}")
    public Result<String> deleteFaculty(@PathVariable Integer id) {
        try {
            // 校验参数
            if (id == null || id <= 0) {
                return Result.error(400, "学院ID不能为空且必须大于0");
            }

            // 检查学院是否存在
            Faculty faculty = officeService.getFacultyById(id);
            if (faculty == null) {
                return Result.error(404, "学院不存在");
            }

            // 删除学院
            boolean deleted = officeService.deleteFacultyById(id);
            if (deleted) {
                return Result.success("学院删除成功");
            } else {
                return Result.error(500, "学院删除失败");
            }
        } catch (IllegalStateException e) {
            return Result.error(400, e.getMessage());
        } catch (Exception e) {
            return Result.error(500, "删除学院失败: " + e.getMessage());
        }
    }

    /**
     * 删除专业
     */
    @DeleteMapping("/deleteMajor/{id}")
    public Result<String> deleteMajor(@PathVariable Integer id) {
        try {
            // 校验参数
            if (id == null || id <= 0) {
                return Result.error(400, "专业ID不能为空且必须大于0");
            }

            // 删除专业
            boolean deleted = officeService.deleteMajorById(id);
            if (deleted) {
                return Result.success("专业删除成功");
            } else {
                return Result.error(404, "专业不存在或删除失败");
            }
        } catch (Exception e) {
            return Result.error(500, "删除专业失败: " + e.getMessage());
        }
    }

    /**
     * 删除辅导员
     */
    @DeleteMapping("/deleteCounselor/{id}")
    public Result<String> deleteCounselor(@PathVariable Integer id) {
        try {
            // 校验参数
            if (id == null || id <= 0) {
                return Result.error(400, "辅导员ID不能为空且必须大于0");
            }

            // 检查辅导员是否存在
            Counselor counselor = officeService.getCounselorById(id);
            if (counselor == null) {
                return Result.error(404, "辅导员不存在");
            }

            // 删除辅导员
            boolean deleted = officeService.deleteCounselorById(id);
            if (deleted) {
                return Result.success("辅导员删除成功");
            } else {
                return Result.error(500, "辅导员删除失败");
            }
        } catch (Exception e) {
            return Result.error(500, "删除辅导员失败: " + e.getMessage());
        }
    }

    /**
     * 添加待缴费项目
     */
    @PostMapping("/createPayItem")
    public Result<Pay> createPayItem(@RequestBody CreatePayRequest request) {
        try {
            Pay payItem = payService.createPayItem(request);
            return Result.success(payItem);
        } catch (IllegalArgumentException e) {
            return Result.error(400, e.getMessage());
        } catch (Exception e) {
            return Result.error(500, "创建缴费项目失败: " + e.getMessage());
        }
    }

    /**
     * 绑定支付项目与学生
     */
    @PostMapping("/bindPayToStudents")
    public Result<String> bindPayToStudents(@RequestBody BindPayRequest request) {
        try {
            int count = payService.bindPayToStudents(request);
            return Result.success("成功绑定 " + count + " 条记录");
        } catch (IllegalArgumentException e) {
            return Result.error(400, e.getMessage());
        } catch (Exception e) {
            return Result.error(500, "绑定支付项目失败: " + e.getMessage());
        }
    }
    
    /**
     * 文件传输接口，经过身份校验后，将文件转发到指定URL
     */
    @PostMapping("/transferFile")
    public Result<String> transferFile(@RequestParam("file") MultipartFile file) {
        try {
            // 身份校验已经在@PreAuthorize注解中完成
            
            // 使用Feign客户端转发文件
            ResponseEntity<String> response = fileTransferFeignClient.transferFile(file);
            
            // 返回转发结果
            if (response.getStatusCode().is2xxSuccessful()) {
                return Result.success("文件转发成功: " + response.getBody());
            } else {
                return Result.error(response.getStatusCode().value(), "文件转发失败: " + response.getBody());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(500, "文件转发异常: " + e.getMessage());
        }
    }
}